package com.atguigu.tingshu.search.receiver;

import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.search.service.SearchService;
import com.atguigu.tingshu.vo.album.TrackStatMqVo;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author: atguigu
 * @create: 2025-03-12 15:50
 */
@Slf4j
@Component
public class SearchReceiver {

    @Autowired
    private SearchService searchService;

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 监听专辑上架消息
     * @param albumId
     * @param message
     * @param channel
     */
    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            exchange =  @Exchange(MqConst.EXCHANGE_ALBUM),
            value = @Queue(MqConst.QUEUE_ALBUM_UPPER),
            key = MqConst.ROUTING_ALBUM_UPPER
    ))
    public void upperAlbum(Long albumId, Message message, Channel channel) {
        if(albumId!=null){
            log.info("[搜索服务]监听到上架消息:{}", albumId);
            searchService.upperAlbum(albumId);
        }
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }


    /**
     * 监听专辑下架消息
     * @param albumId
     * @param message
     * @param channel
     */
    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            exchange =  @Exchange(MqConst.EXCHANGE_ALBUM),
            value = @Queue(MqConst.QUEUE_ALBUM_LOWER),
            key = MqConst.ROUTING_ALBUM_LOWER
    ))
    public void lowerAlbum(Long albumId, Message message, Channel channel) {
        if(albumId!=null){
            log.info("[搜索服务]监听到下架消息:{}", albumId);
            searchService.lowerAlbum(albumId);
        }
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }


    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(value = MqConst.EXCHANGE_TRACK, durable = "true"),
            value = @Queue(value = MqConst.QUEUE_ALBUM_ES_STAT_UPDATE, durable = "true"),
            key = MqConst.ROUTING_TRACK_STAT_UPDATE
    ))
    public void updateAlbumStat(TrackStatMqVo trackStatMqVo, Message message, Channel channel) {
        if (trackStatMqVo != null) {
            log.info("监听到更新声音统计消息，trackStatMqVo:{}", trackStatMqVo);
            //1.消费者幂等性处理，避免同一个统计MQ消息被消费者多次消费 采用Redis set ex nx 命令实现
            String key = RedisConstant.BUSINESS_PREFIX +"es:"+ trackStatMqVo.getBusinessNo();
            Boolean flag = redisTemplate.opsForValue().setIfAbsent(key, "", 10, TimeUnit.MINUTES);
            if (flag) {
                try {
                    //2.调用业务逻辑层更新专辑统计信息
                    searchService.updateAlbumStat(trackStatMqVo);
                } catch (Exception e) {
                    //业务处理发生异常将幂等性缓存key删除
                    redisTemplate.delete(key);
                    //确认消息消费失败，将消息再次入队，重新发送消息
                    channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
                    return;
                }
            }
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }
    }
}
